Android中使用@IntDef @Retention @StringDef

在Android开发中官网不推荐使用枚举enums。

占用内存多(Enums often require more than twice as much memory as static constants.)。 Android中当你的App启动后系统会给App单独分配一块内存,App的DEX code、Heap以及运行时的内存分配都会在这块内存中。

使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class MainActivity extends Activity {

//先定义 常量
public static final int RED = 0;
public static final int GREEN = 1;
public static final int BLUE = 2;

//用 @IntDef "包住" 常量,这里使用@IntDef来代替Enum枚举,也可以使用@StringDef。它会像Enum枚举一样在编译时期检查变量的赋值情况!
@IntDef({RED, GREEN, BLUE})
// @Retention 定义策略,是默认注解
@Retention(RetentionPolicy.SOURCE) ///表示注解所存活的时间,在运行时,而不会存在 .class 文件中
//接口定义
public @interface ColorTypes {}

@ColorTypes int mColor = RED ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setColorType(GREEN);

//声明变量,使用时需要设置一个标记
@ColorTypes int colorType = getColorType();

switch (colorType){
case RED:
break;
case GREEN:
break;
case BLUE:
break;
default:
break;
}

}

public void setColorType(@ColorTypes int color) {
this.mColor = color;
}

@ColorTypes
public int getColorType() {
return mColor;
}
}

使用@StringDef

1
2
3
4
@StringDef({
OK,
ERROR
})

注解生命周期

  1. RetentionPolicy.SOURCE 源码注解,编译成.class文件后注解就不存在,用来提示开发者
  2. RetentionPolicy.CLASS CLASS汇编注解,编译成.class文件后注解也还存在,用于自动生成代码
  3. RetentionPolicy.RUNTIME 运行时动态注解,生命周期一直程序运行时都存在,常用于自动注入
0%